﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace TiposComuns.Objectos
{
    /// <summary>
    /// Services for returning an hash of a string
    /// </summary>
    public class HashService
    {
        #region Consts
        public const int NBITS = 4;
        #endregion

        #region Static
        /// <summary>
        /// Given a string, returns the SHA-1 hash value of that string
        /// </summary>
        /// <param name="username">string</param>
        /// <returns>hash value</returns>
        public static byte[] CalculateHash(string username)
        {
            byte[] data = ASCIIEncoding.Default.GetBytes(username);

            SHA1 sha = new SHA1CryptoServiceProvider();
            
            return sha.ComputeHash(data);

            /*byte[] res = new byte[1];
            byte val = 0;
            for (int i = 0; i < 4; i++)
            {
                val = (byte)((val << 1) + Byte.Parse(String.Format("{0}", username[i])));
            }

            res[0] = (byte)(val << 4);
            return res;*/
        }

        /// <summary>
        /// Returns the hash of the combination between age and sex
        /// </summary>
        /// <param name="age">Age</param>
        /// <param name="sex">Sex</param>
        /// <returns></returns>
        public static byte[] CalculateHash(int age, bool sex)
        {
            string sexo = (sex) ? "masculino" : "feminino";
            string[] ages = new string[] 
            { "0-10","10-20","20-30","30-40",
              "40-50","50-60","60-70","70-80","80-90",
              "90-100","100-110","110-120"};
            return HashService.CalculateHash(ages[age / 10] + sexo);            
        }

        /// <summary>
        /// Returns a random hash
        /// </summary>
        /// <returns>Hash</returns>
        public static byte[] RandomHash()
        {
            byte[] hash = new byte[HashService.NBITS];

            new Random().NextBytes(hash);

            return hash;
        }
        #endregion
    }
}
